package com.tsfyun.scm.service.impl.order;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.tsfyun.common.base.dto.Result;
import com.tsfyun.common.base.enums.*;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.ResultUtil;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.common.base.util.TsfPreconditions;
import com.tsfyun.common.base.util.TypeUtils;
import com.tsfyun.scm.base.DataCalling;
import com.tsfyun.scm.client.RateClient;
import com.tsfyun.scm.dto.order.ImpOrderDTO;
import com.tsfyun.scm.dto.order.ImpOrderLogisticsDTO;
import com.tsfyun.scm.dto.order.ImpOrderMemberDTO;
import com.tsfyun.scm.dto.order.ImpOrderMemberSaveDTO;
import com.tsfyun.scm.entity.base.Currency;
import com.tsfyun.scm.entity.customer.*;
import com.tsfyun.scm.entity.logistics.DomesticLogistics;
import com.tsfyun.scm.entity.order.ImpOrder;
import com.tsfyun.scm.entity.order.ImpOrderLogistics;
import com.tsfyun.scm.entity.order.ImpOrderMember;
import com.tsfyun.scm.entity.storage.Warehouse;
import com.tsfyun.scm.service.base.ICurrencyService;
import com.tsfyun.scm.service.base.ISystemCacheService;
import com.tsfyun.scm.service.customer.*;
import com.tsfyun.scm.service.file.IUploadFileService;
import com.tsfyun.scm.service.logistics.IDomesticLogisticsService;
import com.tsfyun.scm.service.order.IImpOrderCheckWrapService;
import com.tsfyun.scm.service.order.IImpOrderMemberService;
import com.tsfyun.scm.service.storage.IWarehouseService;
import com.tsfyun.scm.service.system.ISerialNumberService;
import com.tsfyun.scm.system.vo.BaseDataVO;
import com.tsfyun.scm.system.vo.CountryVO;
import com.tsfyun.scm.system.vo.UnitVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ImpOrderCheckWrapServiceImpl implements IImpOrderCheckWrapService {

    @Autowired
    private ICurrencyService currencyService;

    @Autowired
    private ISystemCacheService systemCacheService;

    @Autowired
    private IWarehouseService warehouseService;

    @Autowired
    private ISupplierTakeInfoService supplierTakeInfoService;

    @Autowired
    private IDomesticLogisticsService domesticLogisticsService;

    @Autowired
    private ICustomerDeliveryInfoService customerDeliveryInfoService;

    @Autowired
    private ISerialNumberService serialNumberService;

    @Autowired
    private RateClient rateClient;

    @Autowired
    private IImpOrderMemberService impOrderMemberService;

    @Override
    public Currency checkWrapCurrency(String currencyName) {
        TsfPreconditions.checkArgument(StringUtils.isNotEmpty(currencyName),new ServiceException("币制不能为空"));
        Currency currency = currencyService.findByName(currencyName);
        TsfPreconditions.checkArgument(Objects.nonNull(currency),new ServiceException(String.format("【%s】币制不存在",currencyName)));
        return currency;
    }

    @Override
    public void checkWrapOverseasLogistics(ImpOrderLogistics impOrderLogistics, ImpOrderLogisticsDTO paramLogisticsDTO,Boolean submitAudit) {
        impOrderLogistics.setDeliveryModeMemo(paramLogisticsDTO.getDeliveryModeMemo());//交货备注
        //境外交货
        if(StringUtils.isNotEmpty(paramLogisticsDTO.getDeliveryMode())) {
            //值清空以防没有重写
            impOrderLogistics.setInExpressType("");//快递类型
            impOrderLogistics.setHkExpress("");//快递公司
            impOrderLogistics.setHkExpressName("");//快递公司
            impOrderLogistics.setHkExpressNo("");//快递单号
            impOrderLogistics.setTakeTime(null);//要求提货时间
            impOrderLogistics.setSupplierTakeInfoId(null);//供应商提货信息
            impOrderLogistics.setTakeLinkCompany("");//提货公司
            impOrderLogistics.setTakeLinkPerson("");//提货联系人
            impOrderLogistics.setTakeLinkTel("");//提货联系人电话
            impOrderLogistics.setTakeAddress("");//提货地址

            BaseDataVO deliveryModeBaseData = systemCacheService.getBaseDataByTpeAndCode(BaseDataTypeEnum.DeliveryMode.getCode(),paramLogisticsDTO.getDeliveryMode());
            Optional.ofNullable(deliveryModeBaseData).orElseThrow(()->new ServiceException("境外交货方式错误"));
            impOrderLogistics.setDeliveryMode(deliveryModeBaseData.getCode());//交货方式编码
            impOrderLogistics.setDeliveryModeName(deliveryModeBaseData.getName());//交货方式名称

            switch (paramLogisticsDTO.getDeliveryMode()) {
                case "ExpressDelivery"://境外快递
                    if(submitAudit) {
                        TsfPreconditions.checkArgument(StringUtils.isNotEmpty(paramLogisticsDTO.getInExpressType()),new ServiceException("请选择境外交货快递类型"));
                    }
                    if(StringUtils.isNotEmpty(paramLogisticsDTO.getInExpressType())) {
                        InExpressTypeEnum inExpressTypeEnum = InExpressTypeEnum.of(paramLogisticsDTO.getInExpressType());
                        Optional.ofNullable(inExpressTypeEnum).orElseThrow(()->new ServiceException("境外交货-快递类型错误"));
                        impOrderLogistics.setInExpressType(inExpressTypeEnum.getCode());
                    }
                    //香港快递公司校验
                    if(StringUtils.isNotEmpty(paramLogisticsDTO.getHkExpress())) {
                        BaseDataVO HkExpress = systemCacheService.getBaseDataByTpeAndCode(BaseDataTypeEnum.HkExpress.getCode(),paramLogisticsDTO.getHkExpress());
                        Optional.ofNullable(HkExpress).orElseThrow(()->new ServiceException("境外交货-快递公司错误"));
                        impOrderLogistics.setHkExpress(HkExpress.getCode());
                        impOrderLogistics.setHkExpressName(HkExpress.getName());
                    }
                    //香港快递单号
                    if(StringUtils.isNotEmpty(paramLogisticsDTO.getHkExpressNo())){
                        //替换中文逗号
                        impOrderLogistics.setHkExpressNo(paramLogisticsDTO.getHkExpressNo().replace("，",","));
                    }
                    break;
                case "TakeDelivery"://提货
                    if(submitAudit) {
                        TsfPreconditions.checkArgument(Objects.nonNull(paramLogisticsDTO.getSupplierTakeInfoId()),new ServiceException("请选择提货信息"));
                        TsfPreconditions.checkArgument(Objects.nonNull(paramLogisticsDTO.getTakeTime()),new ServiceException("请选择提货时间"));
                    }
                    //提货地址信息验证
                    if(Objects.nonNull(paramLogisticsDTO.getSupplierTakeInfoId())) {
                        SupplierTakeInfo supplierTakeInfo = supplierTakeInfoService.getById(paramLogisticsDTO.getSupplierTakeInfoId());
                        Optional.ofNullable(supplierTakeInfo).orElseThrow(()->new ServiceException("境外交货-提货信息不存在请刷新"));

                        //供应商提货信息
                        impOrderLogistics.setSupplierTakeInfoId(supplierTakeInfo.getId());
                        impOrderLogistics.setTakeLinkCompany(supplierTakeInfo.getCompanyName());
                        impOrderLogistics.setTakeLinkPerson(supplierTakeInfo.getLinkPerson());
                        impOrderLogistics.setTakeLinkTel(supplierTakeInfo.getLinkTel());
                        impOrderLogistics.setTakeAddress(supplierTakeInfo.getProvinceName()+supplierTakeInfo.getCityName()+supplierTakeInfo.getAreaName()+supplierTakeInfo.getAddress());
                    }
                    //提货时间
                    impOrderLogistics.setTakeTime(paramLogisticsDTO.getTakeTime());
                    break;
            }
        }
    }

    @Override
    public void checkWrapDomesticLogistics(ImpOrderLogistics impOrderLogistics, ImpOrderLogisticsDTO paramLogisticsDTO,Boolean submitAudit) {
        impOrderLogistics.setReceivingModeMemo(paramLogisticsDTO.getReceivingModeMemo()); //收货备注
        //国内配送
        if(StringUtils.isNotEmpty(paramLogisticsDTO.getReceivingMode())) {
            impOrderLogistics.setIsCharterCar(Boolean.FALSE);//中港包车
            impOrderLogistics.setPaymentDelivery("");//送货付款方式
            impOrderLogistics.setLogisticsCompanyId(null);//物流公司
            impOrderLogistics.setLogisticsCompanyName("");//物流公司
            impOrderLogistics.setPrescription("");//物流时效要求
            impOrderLogistics.setSelfWareId(null);//提货仓库
            impOrderLogistics.setSelfWareName("");//提货仓库
            impOrderLogistics.setSelfLinkPerson("");//提货联系人电话
            impOrderLogistics.setSelfPersonId("");//提货人身份证号
            impOrderLogistics.setSelfMemo("");//提货备注
            impOrderLogistics.setCustomerDeliveryInfoId(null);//收货信息
            impOrderLogistics.setDeliveryCompanyName("");
            impOrderLogistics.setDeliveryLinkPerson("");
            impOrderLogistics.setDeliveryLinkTel("");
            impOrderLogistics.setDeliveryAddress("");

            BaseDataVO receivingModeBaseData = systemCacheService.getBaseDataByTpeAndCode(BaseDataTypeEnum.ReceivingMode.getCode(),paramLogisticsDTO.getReceivingMode());
            Optional.ofNullable(receivingModeBaseData).orElseThrow(()->new ServiceException("国内配送-送货方式错误"));
            impOrderLogistics.setReceivingMode(receivingModeBaseData.getCode());
            impOrderLogistics.setReceivingModeName(receivingModeBaseData.getName());

            if(Objects.equals("ThirdLogistics",paramLogisticsDTO.getReceivingMode())) {//第三方物流
                if(submitAudit) {
                    TsfPreconditions.checkArgument(Objects.nonNull(paramLogisticsDTO.getLogisticsCompanyId()),new ServiceException("请选择国内配送-物流公司"));
                    TsfPreconditions.checkArgument(Objects.nonNull(paramLogisticsDTO.getCustomerDeliveryInfoId()),new ServiceException("请选择国内配送-收货信息"));
                }
                //国内送货付款方式
                impOrderLogistics.setPaymentDelivery(paramLogisticsDTO.getPaymentDelivery());
                if(Objects.nonNull(paramLogisticsDTO.getLogisticsCompanyId())) {
                    DomesticLogistics domesticLogistics = domesticLogisticsService.getById(paramLogisticsDTO.getLogisticsCompanyId());
                    Optional.ofNullable(domesticLogistics).orElseThrow(()->new ServiceException("国内配送-物流公司错误"));
                    //物流公司
                    impOrderLogistics.setLogisticsCompanyId(domesticLogistics.getId());
                    impOrderLogistics.setLogisticsCompanyName(domesticLogistics.getName());
                    impOrderLogistics.setPrescription(paramLogisticsDTO.getPrescription());
                }
                //客户收货地址信息
                if(Objects.nonNull(paramLogisticsDTO.getCustomerDeliveryInfoId())) {
                    CustomerDeliveryInfo customerDeliveryInfo = customerDeliveryInfoService.getById(paramLogisticsDTO.getCustomerDeliveryInfoId());
                    Optional.ofNullable(customerDeliveryInfo).orElseThrow(()->new ServiceException("国内配送-收货信息错误请刷新"));
                    impOrderLogistics.setCustomerDeliveryInfoId(customerDeliveryInfo.getId());
                    impOrderLogistics.setDeliveryCompanyName(customerDeliveryInfo.getCompanyName());
                    impOrderLogistics.setDeliveryLinkPerson(customerDeliveryInfo.getLinkPerson());
                    impOrderLogistics.setDeliveryLinkTel(customerDeliveryInfo.getLinkTel());
                    impOrderLogistics.setDeliveryAddress(customerDeliveryInfo.getProvinceName()+customerDeliveryInfo.getCityName()+customerDeliveryInfo.getAreaName()+customerDeliveryInfo.getAddress());
                }
            } else if(Objects.equals("SelfLifting",paramLogisticsDTO.getReceivingMode())) {
                //提交审核-自提必须填写提货人相关信息
                if(submitAudit) {
                    TsfPreconditions.checkArgument(Objects.nonNull(paramLogisticsDTO.getSelfWareId()),new ServiceException("请选择国内配送-自提点"));
                    TsfPreconditions.checkArgument(StringUtils.isNotEmpty(paramLogisticsDTO.getSelfLinkPerson()),new ServiceException("国内配送-提货姓名电话不能为空"));
                    TsfPreconditions.checkArgument(StringUtils.isNotEmpty(paramLogisticsDTO.getSelfPersonId()),new ServiceException("国内配送-提货人身份证号码不能为空"));
                }
                if(Objects.nonNull(paramLogisticsDTO.getSelfWareId())){
                    //自提仓库信息
                    Warehouse warehouse = warehouseService.getById(paramLogisticsDTO.getSelfWareId());
                    Optional.ofNullable(warehouse).orElseThrow(()->new ServiceException("国内配送-自提点信息错误"));
                    impOrderLogistics.setSelfWareId(warehouse.getId());
                    impOrderLogistics.setSelfWareName(warehouse.getName());
                }
                impOrderLogistics.setSelfLinkPerson(paramLogisticsDTO.getSelfLinkPerson());
                impOrderLogistics.setSelfPersonId(paramLogisticsDTO.getSelfPersonId());
                impOrderLogistics.setSelfMemo(paramLogisticsDTO.getSelfMemo());
            } else if(Objects.equals("HkThrough",paramLogisticsDTO.getReceivingMode()) || Objects.equals("SpecialCar",paramLogisticsDTO.getReceivingMode()) ) {
                if(submitAudit) {
                    TsfPreconditions.checkArgument(Objects.nonNull(paramLogisticsDTO.getCustomerDeliveryInfoId()),new ServiceException("请选择国内配送-收货信息"));
                }
                //客户收货地址信息
                if(Objects.nonNull(paramLogisticsDTO.getCustomerDeliveryInfoId())) {
                    CustomerDeliveryInfo customerDeliveryInfo = customerDeliveryInfoService.getById(paramLogisticsDTO.getCustomerDeliveryInfoId());
                    Optional.ofNullable(customerDeliveryInfo).orElseThrow(()->new ServiceException("国内配送-收货信息错误请刷新"));
                    impOrderLogistics.setCustomerDeliveryInfoId(customerDeliveryInfo.getId());
                    impOrderLogistics.setDeliveryCompanyName(customerDeliveryInfo.getCompanyName());
                    impOrderLogistics.setDeliveryLinkPerson(customerDeliveryInfo.getLinkPerson());
                    impOrderLogistics.setDeliveryLinkTel(customerDeliveryInfo.getLinkTel());
                    impOrderLogistics.setDeliveryAddress(customerDeliveryInfo.getProvinceName()+customerDeliveryInfo.getCityName()+customerDeliveryInfo.getAreaName()+customerDeliveryInfo.getAddress());
                }
                //是否包车
                impOrderLogistics.setIsCharterCar(Objects.equals(paramLogisticsDTO.getReceivingMode(),"HkThrough"));
            }
        }
    }

    @Override
    public ImpOrderMemberSaveDTO checkWrapOrderMember(ImpOrder order,List<ImpOrderMemberDTO> paramMembers, Boolean submitAudit) {
        //订单数据合计
        order.setTotalPrice(BigDecimal.ZERO);//委托金额
        order.setDecTotalPrice(BigDecimal.ZERO);//报关金额
        order.setTotalCartonNum(0);//总箱数
        order.setTotalMember(paramMembers.size());//产品条数
        order.setTotalNetWeight(BigDecimal.ZERO);//总净重
        order.setTotalCrossWeight(BigDecimal.ZERO);//总毛重
        //成交方式
        TransactionModeEnum transactionMode = TransactionModeEnum.of(order.getTransactionMode());

        List<ImpOrderMember> saveOrderMembers = Lists.newArrayList();
        Map<Long,ImpOrderMember> orderMemberMap = new ConcurrentHashMap<>();
        if(Objects.nonNull(order.getId())) {
            //修改订单查询订单原始明细数据
            List<ImpOrderMember> oldImpOrderMembers = impOrderMemberService.getByOrderId(order.getId());
            if(CollUtil.isNotEmpty(oldImpOrderMembers)) {
                orderMemberMap = oldImpOrderMembers.stream().collect(Collectors.toMap(ImpOrderMember::getId, Function.identity()));
            }
        }
        Map<String, CountryVO> countryVOMap = Maps.newHashMap();
        Map<String, UnitVO> unitVOMap = Maps.newHashMap();
        if(CollUtil.isNotEmpty(paramMembers)) {
            for(int i = 0,length = paramMembers.size(); i < length; i++) {
                final Integer rowNo = i + 1;
                ImpOrderMemberDTO impOrderMemberDTO = paramMembers.get(i);
                //如果是新增订单，则订单明细id置空防止误判
                if(Objects.isNull(order.getId())) {
                    impOrderMemberDTO.setId(null);
                }

                ImpOrderMember impOrderMember;
                if(Objects.isNull(impOrderMemberDTO.getId())) {
                   impOrderMember = new ImpOrderMember();
                    //部分非空字段赋初始值
                    impOrderMember.setTariffRate(BigDecimal.ZERO);
                    impOrderMember.setLevyVal(BigDecimal.ZERO);
                    impOrderMember.setAddedTaxTate(BigDecimal.ZERO);
                    impOrderMember.setTariffRateVal(BigDecimal.ZERO);
                    impOrderMember.setAddedTaxTateVal(BigDecimal.ZERO);
                    impOrderMember.setExciseTaxVal(BigDecimal.ZERO);
                    impOrderMember.setRdutyPaidVal(BigDecimal.ZERO);
                    impOrderMember.setDutyPaidVal(BigDecimal.ZERO);
                    impOrderMember.setRtariffRateVal(BigDecimal.ZERO);
                    impOrderMember.setRaddedTaxTateVal(BigDecimal.ZERO);
                    impOrderMember.setRexciseTaxVal(BigDecimal.ZERO);
                } else {
                   impOrderMember = orderMemberMap.get(impOrderMemberDTO.getId());
                   TsfPreconditions.checkArgument(Objects.nonNull(impOrderMember),new ServiceException(String.format("第%d行订单明细数据不存在，请删除该明细重新填写",rowNo)));
                   //数据库存在且用户也提交过来的排除掉
                   orderMemberMap.remove(impOrderMemberDTO.getId());
                }
                //型号
                impOrderMember.setModel(impOrderMemberDTO.getModel().toUpperCase());
                //品牌
                impOrderMember.setBrand(impOrderMemberDTO.getBrand().toUpperCase());
                //品名
                impOrderMember.setName(impOrderMemberDTO.getName());
                //验货前端不需要更改
                if(impOrderMemberDTO.getSpec()!=null){
                    //规格参数
                    impOrderMember.setSpec(impOrderMemberDTO.getSpec());
                }
                //客户物料号
                impOrderMember.setGoodsCode(impOrderMemberDTO.getGoodsCode());
                //数量
                impOrderMember.setQuantity(StringUtils.rounded2(TypeUtils.castToBigDecimal(impOrderMemberDTO.getQuantity(), BigDecimal.ZERO)));
                //总价
                impOrderMember.setTotalPrice(StringUtils.rounded2(TypeUtils.castToBigDecimal(impOrderMemberDTO.getTotalPrice(), BigDecimal.ZERO)));
                //净重
                impOrderMember.setNetWeight(StringUtils.rounded4(TypeUtils.castToBigDecimal(impOrderMemberDTO.getNetWeight(), BigDecimal.ZERO)));
                //毛重
                impOrderMember.setGrossWeight(StringUtils.rounded4(TypeUtils.castToBigDecimal(impOrderMemberDTO.getGrossWeight(), BigDecimal.ZERO)));
                //箱数
                impOrderMember.setCartonNum(TypeUtils.castToInt(impOrderMemberDTO.getCartonNum(),0));
                //箱号(修改订单前端未传，空字符串允许保存)
                if(impOrderMemberDTO.getCartonNo()!=null){
                    impOrderMember.setCartonNo(impOrderMemberDTO.getCartonNo());
                }
                //单价
                impOrderMember.setUnitPrice(impOrderMember.getQuantity().compareTo(BigDecimal.ZERO) == 1 ?
                        StringUtils.rounded4(impOrderMember.getTotalPrice().divide(impOrderMember.getQuantity(),4,BigDecimal.ROUND_HALF_UP))
                        : BigDecimal.ZERO);

                //校验单位
                if(StringUtils.isNotEmpty(impOrderMemberDTO.getUnitName())){
                    UnitVO unitVO = unitVOMap.get(impOrderMemberDTO.getUnitName());
                    if(Objects.isNull(unitVO)) {
                        unitVO = systemCacheService.getUnitByName(impOrderMemberDTO.getUnitName());
                        Optional.ofNullable(unitVO).orElseThrow(()->new ServiceException(String.format("订单明细第%d行单位错误",rowNo)));
                    }
                    impOrderMember.setUnitCode(unitVO.getId());
                    impOrderMember.setUnitName(unitVO.getName());
                    unitVOMap.put(impOrderMemberDTO.getUnitName(),unitVO);
                }

                //校验国家
                if(StringUtils.isNotEmpty(impOrderMemberDTO.getCountryName())) {
                    CountryVO countryVO = countryVOMap.get(impOrderMemberDTO.getCountryName());
                    if(Objects.isNull(countryVO)) {
                        countryVO = systemCacheService.getCountryByName(impOrderMemberDTO.getCountryName());
                        Optional.ofNullable(countryVO).orElseThrow(()->new ServiceException(String.format("订单明细第%d行产地错误",rowNo)));
                    }
                    impOrderMember.setCountry(countryVO.getId());
                    impOrderMember.setCountryName(countryVO.getName());
                    countryVOMap.put(impOrderMemberDTO.getCountryName(),countryVO);
                }
                impOrderMember.setDecTotalPrice(impOrderMember.getTotalPrice());
                impOrderMember.setDecUnitPrice(impOrderMember.getUnitPrice());
                //成交方式CIF
                if(Objects.equals(TransactionModeEnum.CIF,transactionMode)){
                    BigDecimal rate = DataCalling.getInstance().impCIFRate().divide(BigDecimal.valueOf(100),6,BigDecimal.ROUND_HALF_UP).add(BigDecimal.ONE);
                    //报关总价
                    impOrderMember.setDecTotalPrice(impOrderMember.getTotalPrice().multiply(rate).setScale(2,BigDecimal.ROUND_HALF_UP));
                    //报关单价
                    impOrderMember.setDecUnitPrice(
                            impOrderMember.getQuantity().compareTo(BigDecimal.ZERO)==1?
                                    impOrderMember.getTotalPrice().multiply(rate).divide(impOrderMember.getQuantity(),4,BigDecimal.ROUND_HALF_UP)
                                    :BigDecimal.ZERO);
                }
                order.setTotalPrice(order.getTotalPrice().add(impOrderMember.getTotalPrice()).setScale(2,BigDecimal.ROUND_HALF_UP));
                order.setDecTotalPrice(order.getDecTotalPrice().add(impOrderMember.getDecTotalPrice()).setScale(2,BigDecimal.ROUND_HALF_UP));
                order.setTotalCartonNum(order.getTotalCartonNum()+impOrderMember.getCartonNum());
                order.setTotalNetWeight(order.getTotalNetWeight().add(impOrderMember.getNetWeight()).setScale(4,BigDecimal.ROUND_HALF_UP));
                order.setTotalCrossWeight(order.getTotalCrossWeight().add(impOrderMember.getGrossWeight()).setScale(4,BigDecimal.ROUND_HALF_UP));
                saveOrderMembers.add(impOrderMember);
            }
        }
        if(order.getTotalNetWeight().compareTo(order.getTotalCrossWeight())==1){
            throw new ServiceException("总净重不能大于总毛重");
        }
        return new ImpOrderMemberSaveDTO(saveOrderMembers,orderMemberMap.values().stream().collect(Collectors.toList()));
    }

    @Override
    public void wrapOrderValue(ImpOrder impOrder, List<ImpOrderMember> orderMembers, ImpOrderDTO paramOrderDTO,Boolean submitAudit) {
        //业务类型
        impOrder.setBusinessType(paramOrderDTO.getBusinessType());
        //成交方式
        impOrder.setTransactionMode(paramOrderDTO.getTransactionMode());
        //客户单号
        impOrder.setClientNo(paramOrderDTO.getClientNo());
        //备注
        //impOrder.setMemo(paramOrderDTO.getMemo());
        //订单总箱数，总净重，总毛重，总委托金额，总报关金额
        impOrder.setTotalCartonNum(orderMembers.stream().mapToInt(ImpOrderMember::getCartonNum).sum());
        impOrder.setTotalNetWeight(StringUtils.rounded4(orderMembers.stream().map(ImpOrderMember::getNetWeight).reduce(BigDecimal.ZERO,BigDecimal::add)));
        impOrder.setTotalCrossWeight(StringUtils.rounded4(orderMembers.stream().map(ImpOrderMember::getGrossWeight).reduce(BigDecimal.ZERO,BigDecimal::add)));
        impOrder.setTotalPrice(StringUtils.rounded2(orderMembers.stream().map(ImpOrderMember::getTotalPrice).reduce(BigDecimal.ZERO,BigDecimal::add)));
        impOrder.setDecTotalPrice(StringUtils.rounded2(orderMembers.stream().map(ImpOrderMember::getDecTotalPrice).reduce(BigDecimal.ZERO,BigDecimal::add)));
        //订单状态
        //impOrder.setStatusId(Objects.equals(submitAudit,Boolean.TRUE) ? OrderStatusEnum.WAIT_EXAMINE.getCode() : OrderStatusEnum.TEMP_SAVED.getCode());
        //订单日期
        impOrder.setOrderDate(LocalDateTime.now());
        if(!Objects.equals(submitAudit,Boolean.TRUE) && StringUtils.isEmpty(impOrder.getDocNo())) {
            //暂存生成订单号
            String docNo = serialNumberService.generateDocNo(SerialNumberTypeEnum.IMP_ORDER);
            impOrder.setDocNo(docNo);
        }
        //提交审核需要验证海关汇率
        if(submitAudit) {
            Result<BigDecimal> customsRateResult =  rateClient.thisMonth(impOrder.getCurrencyId());
            ResultUtil.checkRemoteResult(customsRateResult,"获取当月海关汇率数据失败，请稍后再试");
            TsfPreconditions.checkArgument(Objects.nonNull(customsRateResult.getData()),new ServiceException("当月海关汇率还未公布请联系客服人员手工录入"));
            impOrder.setImpRate(customsRateResult.getData());
            //总毛重必须大于0
            TsfPreconditions.checkArgument(impOrder.getTotalCrossWeight().compareTo(BigDecimal.ZERO) == 1,new ServiceException("总毛重必须大于0"));
            //总净重不能大于总毛重
            TsfPreconditions.checkArgument(impOrder.getTotalNetWeight().compareTo(impOrder.getTotalCrossWeight()) == -1,new ServiceException("总净重不能大于总毛重"));

            if(!Objects.equals(impOrder.getCurrencyId(),"USD")) {
                Result<BigDecimal> usdCustomsRateResult =  rateClient.thisMonth("USD");
                ResultUtil.checkRemoteResult(usdCustomsRateResult,"获取当月海关汇率数据失败，请稍后再试");
                TsfPreconditions.checkArgument(Objects.nonNull(usdCustomsRateResult.getData()),new ServiceException("当月海关汇率还未公布请联系客服人员手工录入"));
                impOrder.setUsdRate(usdCustomsRateResult.getData());
            }
        }
    }
}
